package com.xk.auth.controller;

import com.hy.common.enums.ExceptionEnums;
import com.hy.common.exception.XkException;
import com.hy.common.utils.CookieUtils;
import com.xk.auth.config.JwtProperties;
import com.xk.auth.entiy.UserInfo;
import com.xk.auth.service.AuthService;
import com.xk.auth.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录授权
 */
@Controller
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {
    @Autowired
    private AuthService authService;
    @Autowired
    private JwtProperties prop;

    @PostMapping("login")
    public ResponseEntity<Void> login(@RequestParam("username") String username,
                                      @RequestParam("password") String password,
                                      HttpServletRequest request, HttpServletResponse response){

        //用户登录
        String token=authService.login(username,password);
        //写入到cookie中
        CookieUtils.newBuilder(response).httpOnly().request(request).build("XK_TOKEN",token);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 校验用户登录状态
     * @param token
     * @return
     */
    @GetMapping("verify")
        public ResponseEntity<UserInfo> verify(@CookieValue("XK_TOKEN") String token,
                                               HttpServletRequest request, HttpServletResponse response){
        //如果没有token,证明未登录，返回403
        if (StringUtils.isBlank(token)){
            throw new XkException(ExceptionEnums.UNAUTHORIZED);
        }
        //解析token,第二个参数是公钥，解析需要公钥
        try {
            UserInfo info = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
            //刷新token,重新生成token,然后再写入到cookie中
            String newToken = JwtUtils.generateToken(info, prop.getPrivateKey(), prop.getExpire());
            //写入到cookie中
            CookieUtils.newBuilder(response).httpOnly().request(request).build("XK_TOKEN",token);
            //已登录，返回用户信息
            return ResponseEntity.ok(info);
        }catch (Exception e){
            //token已过期或token被篡改
            throw new XkException(ExceptionEnums.UNAUTHORIZED);
        }
    }
}
